package implementation;
import interfaces.*;

import java.util.Date;
import java.util.LinkedList;


public class IFindItemImpl implements IFindItem {
	
	private IItemCache cache;
	private ISearchSubSupplier subSupplier;
	private long hours;

	public IFindItemImpl(IItemCache cache, ISearchSubSupplier subSupplier){
		this.cache = cache;
		this.subSupplier = subSupplier;
		this.hours = 0;
	}
	
	
	@Override
	public LinkedList<IItem> LookUpItem(long partnumber, String description) {
		LinkedList<IItem>  results = new LinkedList<IItem>();
		
		results  = cache.LookUpItem(partnumber, description);
		
		if(!results.isEmpty()){
			LinkedList<IItem> toBeRemoved= new LinkedList<IItem>();
			Date currentTime = new Date();
			for(IItem item: results){
				long age= (currentTime.getTime() - item.getHit().getTime())/(3600*1000);
				if(age>hours){
					toBeRemoved.add(item);
				}
			}
			cache.RemoveItems(toBeRemoved);
			results = cache.LookUpItem(partnumber, description);
		}
		
		if(results.isEmpty()){
			results = subSupplier.LookUpItem(partnumber, description);
			if(!results.isEmpty()) {
				cache.AddItems(results);
			}
		}
		return results;
	}

	@Override
	public void SetCacheExpireTime(int hours) {
		this.hours = hours;
	}

}
